package com.stillalive.springbootbooksystem.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stillalive.springbootbooksystem.Model.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
// 拦截所有相应，对于不同数据类型返回统一的Result类型值，统一后端返回值
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //false: 不处理  true: 处理
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // 处理String类型
        if (body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }
        // 处理Result类型
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}